// 导入存储服务 - 使用更稳定的绝对路径导入
const storageService = require('../../../services/storage')
import * as comm from '../../../utils/common';
import {
  Base64
} from '../../../utils/base64';
const playerModeService = require('../../../services/player_mode_service')

// 获取 App 实例
const appInstance = getApp();

Page({
  data: {
    showOtaUpdate: false,
    otaStatusText: '点击检测是否有可更新固件',
    hasUpdate: false,
    isChecking: false, // 添加检测状态标志
    showCustomToast: false,
    toastText: '',
    toastType: 'success',
    // 通道配置相关
    showChannelConfig: false,
    originalChannelConfigs: null, // 用于取消操作时恢复
    showChannelEdit: false,
    editingChannel: null,
    // 默认通道配置
    channelConfigs: [],
    // 初始化currentPositionIndex
    currentPositionIndex: 0,
    // 初始化buttonStyles，避免undefined错误
    buttonStyles: {
      button1: {
        left: '40rpx',
        top: '230rpx',
        width: '140rpx',
        height: '140rpx',
      },
      button2: {
        left: '250rpx',
        top: '30rpx',
        width: '200rpx',
        height: '200rpx',
      },
      button3: {
        left: '520rpx',
        top: '210rpx',
        width: '140rpx',
        height: '140rpx',
      },
      button4: {
        left: '350rpx',
        top: '350rpx',
        width: '140rpx',
        height: '140rpx',
      },
    },
    buttonPositions: [{
        id: 'button1',
        left: '40rpx',
        top: '230rpx',
        width: '140rpx',
        height: '140rpx',
      },
      {
        id: 'button2',
        left: '250rpx',
        top: '30rpx',
        width: '200rpx',
        height: '200rpx',
      },
      {
        id: 'button3',
        left: '520rpx',
        top: '210rpx',
        width: '140rpx',
        height: '140rpx',
      },
      {
        id: 'button4',
        left: '350rpx',
        top: '350rpx',
        width: '140rpx',
        height: '140rpx',
      },
    ],
    buttonContents: {
      button1: {
        text: '模式1',
        color: '#FFFFFF',
        textRotation: '0deg',
      },
      button2: {
        text: '模式2',
        color: '#FFFFFF',
        textRotation: '0deg',
      },
      button3: {
        text: '模式3',
        color: '#FFFFFF',
        textRotation: '0deg',
      },
      button4: {
        text: '模式4',
        color: '#FFFFFF',
        textRotation: '0deg',
      },
    },
    // 临时开关相关数据
    showTempSwitch: false,
    lightModes: [],
    lightModeIndex: 0,
    tempSwitchDuration: '40',
    // 配置数据相关
    showConfigData: false,
    deviceModel: '淡水灯',
    firmwareVersion: '1.0.0',
    maxPower: '100',
    isModelDisabled: true,
    isVersionDisabled: true,
    isPowerDisabled: false,
    originalConfigData: null,
    configName: '输入配置名称',
    savedConfigs: [], // 保存的配置列表
    currentConfigData: null, // 当前配置数据
    maxConfigsCount: 20, // 最多保存20条配置
    configShareCode: '', // 配置分享码
    showConfigManager: false, // 配置管理弹窗显示状态
    selectedConfigIndex: -1, // 当前选中的配置索引
    showImportCodeModal: false,
    importCodeValue: '',
    showShareCodeResult: false,
    shareCodeData: null,

    did: null,
    device: null,
    imgName: null,
    host: "www.99666666.xyz",
    port: 80,
    verObj: {
      "t": "",
      "v": 0,
      "s": ""
    },
    presets: [],
    timeoutObj: null,
    isGroup: false,
    devices: [],
    syncNum: 0,
  },

  // 批量更新数据方法，用于合并多个setData调用
  batchUpdate: function (updateData) {
    if (!this._pendingUpdate) {
      this._pendingUpdate = {};

      // 使用nextTick延迟到下一个时间片执行更新
      wx.nextTick(() => {
        // 执行所有累积的更新
        this.setData(this._pendingUpdate);
        this._pendingUpdate = null;
      });
    }

    // 合并更新对象
    Object.assign(this._pendingUpdate, updateData);
  },

  onLoad: function (options) {
    console.log("mode_setting onLoad...")
    console.log(options);
    this.setData({
      did: options.did
    });

    let isGroup = false
    let dobj = storageService.getDeviceInfo(options.did)
    this.data.device = dobj
    if (dobj.deviceId.startsWith('group_')) {
      isGroup = true
      const devices = storageService.batchGetDeviceInfo(dobj.deviceIds)
      this.data.devices = [...devices]
    }

    if (!isGroup) {
      let tvobj = appInstance.deviceVerMap[this.data.did];
      if (!comm.isEmptyObj(tvobj)) {
        this.verObj = JSON.parse(JSON.stringify(tvobj));
      }
    }

    let entityId = options.did
    let deviceType = dobj.deviceType

    this.loadAllModeSettings(entityId, isGroup, deviceType) // **传递 deviceType**
    const chs = storageService.getDeviceChannels(this.data.did)
    const channelConfigs = []
    chs.forEach(ele => {
      channelConfigs.push({
        n: ele.n,
        name: ele.nm,
        color: ele.c,
        enabled: ele.u == 1
      })
    })
    this.setData({
      channelConfigs,
      isGroup: isGroup
    });
    console.log(this.data.channelConfigs)

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("mode_setting onReady...")
  },

  onHide() {
    console.log("mode_setting onHide...")
    const $t = this
    if (!this.data.isGroup) {
      wx.$event.remove(this.data.device.topicSub, this)
    } else {
      this.data.devices.forEach(device => {
        wx.$event.remove(device.topicSub, $t)
      })
    }
  },

  // 加载所有模式设置数据
  loadAllModeSettings: function (entityId, isGroup, deviceType) {
    if (!entityId) {
      console.error('loadAllModeSettings: entityId is missing')
      return
    }
    try {
      // 使用存储服务获取模式设置数据
      const modeSettingData = storageService.getModeSettingData(entityId, isGroup, deviceType)

      // 加载按钮数据，提供默认值
      const buttonData = modeSettingData.buttonData || {}
      this.setData({
        buttonStyles: buttonData.buttonStyles || this.data.buttonStyles,
        currentPositionIndex: buttonData.currentPositionIndex || 0,
        centerButtonId: buttonData.centerButtonId || 'button2',
      })

      // 加载临时开关设置，提供默认值
      const tempSwitchSettings = modeSettingData.tempSwitchSettings || {}
      this.setData({
        lightModeIndex: tempSwitchSettings.lightModeIndex !== undefined ? tempSwitchSettings.lightModeIndex : 0,
        tempSwitchDuration: tempSwitchSettings.tempSwitchDuration || '40',
      })

      let tempCfg = storageService.getTempInfo(this.data.did)
      this.setData({
        fanStartTemp: tempCfg ? tempCfg.fanStartTemp : 40,
        ntcDiffTemp: tempCfg ? tempCfg.ntcDiffTemp : 0,
        fanStartTempDisplay: Number(tempCfg.fanStartTemp) + Number(tempCfg.ntcDiffTemp),
      })

      //加载模式


    } catch (e) {
      console.error(`加载模式设置数据失败 (ID: ${entityId}, isGroup: ${isGroup})`, e)
      // Optionally set defaults here as well if loading fails
    }
  },

  // 返回上一页
  goBack: function () {
    wx.navigateBack()
  },

  // 触摸开始事件
  touchStart: function (e) {
    this.setData({
      touchStartY: e.touches[0].clientY,
    })
  },

  touchMove(e) {
    return {
      preventDefault: true
    }
  },

  // 触摸结束事件
  touchEnd: function (e) {
    const touchEndY = e.changedTouches[0].clientY
    const moveDistance = touchEndY - this.data.touchStartY

    // 检测是否为下滑手势（移动距离大于50px）
    if (moveDistance > 50) {
      this.rotateButtonsClockwise()
    } else if (moveDistance < -50) {
      this.rotateButtonsCounterClockwise()
    }
  },

  // 顺时针旋转按钮位置
  rotateButtonsClockwise: function () {
    this.rotateButtons(-1)
  },

  // 逆时针旋转按钮位置
  rotateButtonsCounterClockwise: function () {
    this.rotateButtons(1)
  },

  rotateButtons: function (direction) {
    // 更新位置索引
    let newIndex = (this.data.currentPositionIndex + direction + 4) % 4

    // 创建新的按钮位置数组和内容数组
    let newButtonStyles = {}
    let newButtonContents = {}

    // 确保buttonPositions存在
    if (!this.data.buttonPositions) {
      console.error('buttonPositions未定义')
      return
    }

    // 确保buttonContents存在
    if (!this.data.buttonContents) {
      console.error('buttonContents未定义')
      return
    }

    // 为每个按钮分配新的位置和内容
    for (let i = 0; i < 4; i++) {
      const buttonId = `button${i + 1}`
      const newPosIndex = (i + newIndex) % 4
      const newPos = this.data.buttonPositions[newPosIndex]

      // 检查newPos是否存在
      if (!newPos) {
        console.error(`buttonPositions[${newPosIndex}]未定义`)
        return
      }

      // 修正原始按钮索引的计算方式，确保按钮内容正确轮换
      const originalButtonIndex = i
      const originalButtonId = `button${originalButtonIndex + 1}`

      // 设置按钮的新样式（位置和尺寸）
      newButtonStyles[buttonId] = {
        left: newPos.left,
        top: newPos.top,
        width: newPos.width,
        height: newPos.height,
      }

      // 检查buttonContents和对应的按钮内容是否存在
      if (!this.data.buttonContents[originalButtonId]) {
        console.error(`buttonContents[${originalButtonId}]未定义，使用默认值`)
        // 为未定义的按钮内容提供默认值，避免运行时错误
        this.data.buttonContents[originalButtonId] = {
          text: `模式${originalButtonIndex + 1}`,
          color: '#FFFFFF',
          textRotation: '0deg',
        }
      }

      // 设置按钮的新内容（文字和颜色）
      newButtonContents[buttonId] = {
        text: this.data.buttonContents[originalButtonId].text || `模式${originalButtonIndex + 1}`,
        color: this.data.buttonContents[originalButtonId].color || '#FFFFFF',
        textRotation: '0deg',
      }
    }

    // 使用setData更新按钮位置、尺寸、内容和当前索引
    // 使用nextTick确保DOM更新在同一帧内完成，减少抖动
    wx.nextTick(() => {
      this.setData({
        currentPositionIndex: newIndex,
        buttonStyles: newButtonStyles,
        buttonContents: newButtonContents,
      })

      // 保存按钮位置和内容到本地存储
      try {
        const buttonData = {
          buttonStyles: newButtonStyles,
          buttonContents: newButtonContents,
          currentPositionIndex: newIndex,
        }
        storageService.saveModeSettingData(this.data.did, {
          buttonData: buttonData
        }, 0, this.data.device.deviceType)
      } catch (e) {
        console.error('保存按钮数据失败', e)
      }
    })
  },


  // 切换设置弹出模块的显示状态
  toggleSettings: function () {
    // 如果当前设置弹窗是打开状态，则关闭所有弹窗并恢复半圆形按钮组
    if (this.data.showSettingsPopup) {
      this.closeAllPopups()
    } else {
      this.setData({
        showSettingsPopup: true,
      })
    }
  },

  // 关闭所有弹出模块并恢复半圆形按钮组
  closeAllPopups: function () {
    // 检查是否有未保存的散热设置，如果有则恢复到原始值
    if (this.data.showCoolingSettings && this.data.originalCoolingSettings) {
      this.restoreCoolingSettings()
    }

    // 检查是否有未保存的临时开关设置，如果有则恢复到原始值
    if (this.data.showTempSwitch && this.data.originalTempSwitchSettings) {
      this.restoreTempSwitchSettings()
    }

    // 检查是否有未保存的配置数据，如果有则恢复到原始值
    if (this.data.showConfigData && this.data.originalConfigData) {
      this.restoreConfigData()
    }

    // 关闭所有弹窗
    this.setData({
      showSettingsPopup: false,
      showCoolingSettings: false,
      showChannelConfig: false,
      showTempSwitch: false,
      showOtaUpdate: false,
      showConfigData: false,
      semiCircleHidden: false, // 确保半圆按钮组显示
    })
  },

  // Helper function to revert unsaved changes in other popups
  _revertOtherPopups: function (excludePopup) {
    let revertData = {}
    // Revert Cooling Settings if open and unsaved, and not excluded
    if (
      excludePopup !== 'cooling' &&
      this.data.showCoolingSettings &&
      this.data.originalCoolingSettings
    ) {
      revertData.fanStartTemp = this.data.originalCoolingSettings.fanStartTemp
      revertData.ntcDiffTemp = this.data.originalCoolingSettings.ntcDiffTemp
      revertData.fanStartTempDisplay = this.data.originalCoolingSettings.fanStartTempDisplay
      revertData.originalCoolingSettings = null // Clear backup after deciding to revert
      revertData.showCoolingSettings = false // Ensure it's closed
    }
    // Revert Channel Config if open and unsaved, and not excluded
    if (
      excludePopup !== 'channel' &&
      this.data.showChannelConfig &&
      this.data.originalChannelConfigs
    ) {
      revertData.channelConfigs = this.data.originalChannelConfigs
      revertData.originalChannelConfigs = null // Clear backup
      revertData.showChannelConfig = false // Ensure it's closed
    }
    // Revert Temp Switch if open and unsaved, and not excluded
    if (
      excludePopup !== 'tempSwitch' &&
      this.data.showTempSwitch &&
      this.data.originalTempSwitchSettings
    ) {
      revertData.lightModeIndex = this.data.originalTempSwitchSettings.lightModeIndex
      revertData.tempSwitchDuration = this.data.originalTempSwitchSettings.tempSwitchDuration
      revertData.originalTempSwitchSettings = null // Clear backup
      revertData.showTempSwitch = false // Ensure it's closed
    }
    // Revert Config Data if open and unsaved, and not excluded
    if (
      excludePopup !== 'configData' &&
      this.data.showConfigData &&
      this.data.originalConfigData
    ) {
      revertData.deviceModel = this.data.originalConfigData.deviceModel
      revertData.firmwareVersion = this.data.originalConfigData.firmwareVersion
      revertData.maxPower = this.data.originalConfigData.maxPower
      revertData.originalConfigData = null // Clear backup
      revertData.showConfigData = false // Ensure it's closed
    }
    // Apply reverts for other popups if needed
    if (Object.keys(revertData).length > 0) {
      console.log('Reverting unsaved changes in other popups:', Object.keys(revertData))
      this.setData(revertData)
    }
  },

  // 切换散热设置滑动模块的显示状态 (Refined: Reverts others first)
  toggleCoolingSettings: function () {
    // 1. Revert unsaved changes in Channel Config and Temp Switch popups
    this._revertOtherPopups('cooling') // Exclude self

    // 2. Now handle the cooling settings popup itself
    const newShowCoolingSettings = !this.data.showCoolingSettings
    if (newShowCoolingSettings) {
      // Open: Backup current state
      this.setData({
        originalCoolingSettings: {
          // Store backup
          fanStartTemp: this.data.fanStartTemp,
          ntcDiffTemp: this.data.ntcDiffTemp,
          fanStartTempDisplay: this.data.fanStartTempDisplay,
        },
        showCoolingSettings: true,
        showChannelConfig: false, // Ensure others are closed
        showTempSwitch: false,
        showOtaUpdate: false, // Also close OTA
        showConfigData: false, // 确保配置数据弹窗关闭
        semiCircleHidden: true,
      })
    } else {
      // Close: Revert if backup exists (not saved)
      if (this.data.originalCoolingSettings) {
        // Check if backup exists
        this.setData({
          fanStartTemp: this.data.originalCoolingSettings.fanStartTemp,
          ntcDiffTemp: this.data.originalCoolingSettings.ntcDiffTemp,
          fanStartTempDisplay: this.data.originalCoolingSettings.fanStartTempDisplay,
          originalCoolingSettings: null, // Clear backup after restoring
        })
      }
      // Always ensure it's hidden and semi-circle is shown
      this.setData({
        showCoolingSettings: false,
        semiCircleHidden: false, // Show semi-circle when closing
      })
    }
  },


  // 切换通道配置滑动模块的显示状态 (Refined: Reverts others first)
  toggleChannelConfig: function () {
    // 1. 先恢复其他弹窗的未保存修改
    this._revertOtherPopups('channel')

    // 2. 处理通道配置弹窗的显示状态
    const newShowChannelConfig = !this.data.showChannelConfig
    if (newShowChannelConfig) {
      // 检查通道配置是否为空或通道数量不等于10，如果是则初始化为10通道
      let currentChannels = this.data.channelConfigs;

      // 打开通道配置，备份当前配置以便取消时恢复，并创建临时副本供编辑
      this.setData({
        originalChannelConfigs: JSON.parse(JSON.stringify(currentChannels)), // 存储备份
        showChannelConfig: true,
        showCoolingSettings: false, // 确保其他弹窗都已关闭
        showTempSwitch: false,
        showOtaUpdate: false, // 同时关闭OTA
        showConfigData: false, // 确保配置数据弹窗关闭
        showSettingsPopup: true, // 保持设置弹窗显示
        semiCircleHidden: true // 隐藏半圆按钮组
      });
    } else {
      // 关闭通道配置，恢复到打开弹窗前的状态
      if (this.data.originalChannelConfigs) {
        this.setData({
          channelConfigs: this.data.originalChannelConfigs, // 恢复主数据
          originalChannelConfigs: null, // 清除备份
        });
      }

      this.setData({
        showChannelConfig: false,
        semiCircleHidden: false // 显示半圆按钮组
      });
    }
  },

  // 切换临时开关滑动模块的显示状态 (Refined: Reverts others first)
  toggleTempSwitch: function () {
    // 1. Revert unsaved changes in Cooling and Channel Config popups
    this._revertOtherPopups('tempSwitch') // Exclude self

    // 2. Now handle the temp switch popup itself
    const newShowTempSwitch = !this.data.showTempSwitch
    if (newShowTempSwitch) {
      // Open: Backup current state
      this.setData({
        originalTempSwitchSettings: {
          // Store backup
          lightModeIndex: this.data.lightModeIndex,
          tempSwitchDuration: this.data.tempSwitchDuration,
        },
        showTempSwitch: true,
        showCoolingSettings: false, // Ensure others are closed
        showChannelConfig: false,
        showOtaUpdate: false, // Also close OTA
        showConfigData: false, // 确保配置数据弹窗关闭
        semiCircleHidden: true,
      })
    } else {
      // Close: Revert if backup exists (not saved)
      if (this.data.originalTempSwitchSettings) {
        // Check if backup exists
        this.setData({
          lightModeIndex: this.data.originalTempSwitchSettings.lightModeIndex,
          tempSwitchDuration: this.data.originalTempSwitchSettings.tempSwitchDuration,
          originalTempSwitchSettings: null, // 清除备份 after restoring
        })
      }
      // Always ensure it's hidden and semi-circle is shown
      this.setData({
        showTempSwitch: false,
        semiCircleHidden: false, // Show semi-circle when closing
      })
    }
  },

  // 切换OTA升级滑动模块的显示状态 (Refined: Reverts others first)
  toggleOtaUpdate: function () {
    // 1. Revert unsaved changes in Cooling, Channel Config, and Temp Switch popups
    this._revertOtherPopups('ota') // Exclude OTA itself (no backup)

    // 2. Now handle the OTA popup display
    const newShowOtaUpdate = !this.data.showOtaUpdate
    this.setData({
      showOtaUpdate: newShowOtaUpdate, // Toggle OTA display
      // Ensure other setting popups are closed (they should be already by _revertOtherPopups if they were open)
      showCoolingSettings: false,
      showChannelConfig: false,
      showTempSwitch: false,
      showConfigData: false, // 确保配置数据弹窗关闭
      // Hide/show semi-circle based on OTA visibility
      semiCircleHidden: newShowOtaUpdate,
    })
  },

  // 检查并更新固件的统一功能
  checkAndUpdateFirmware: function () {
    // 如果已经有可用更新，则执行升级操作
    if (this.data.hasUpdate) {
      this.startFirmwareUpdate();
    } else {
      // 否则检查是否有更新
      this.checkForFirmwareUpdates();
    }
  },

  // 检查固件更新
  checkForFirmwareUpdates: function () {
    // 显示检测中的状态
    this.setData({
      otaStatusText: '正在检测更新...',
      isChecking: true
    });
    let $t = this;
    comm.httpGet("/version/check?ver=" + $t.verObj.ver, function (res) {
      //res.data = "test.bin"
      if (comm.isEmpty(res.data)) {
        $t.setData({
          otaStatusText: '当前已是最新版本',
          hasUpdate: false,
          isChecking: false
        });

        // 显示已是最新版本提示
        wx.showToast({
          title: '已是最新版本',
          icon: 'none',
          duration: 1500
        });
      } else {
        $t.setData({
          otaStatusText: '发现新版本，可以升级',
          hasUpdate: true,
          isChecking: false,
          imgName: res.data
        });

        // 显示发现更新提示
        wx.showToast({
          title: '有新固件可用',
          icon: 'success',
          duration: 2000
        });
      }
    }, function (error) {
      console.log(error);
      $t.showCustomToast('检查更新异常！', 'error');
    });
  },

  // 开始固件升级过程
  startFirmwareUpdate: function () {
    if (comm.isEmpty(this.data.host) || comm.isEmpty(this.data.port) || comm.isEmpty(this.data.imgName)) {
      this.showCustomToast('参数错误!', 'error');
      return;
    }
    const $t = this
    appInstance.sendMtMsg(this.data.device.topicSend, "updateImg", {
      host: this.data.host,
      port: this.data.port,
      image: this.data.imgName
    }, function (error) {
      if (error) {
        $t.showCustomToast("发送更新固件命令失败!" + error, 'error');
      } else {
        wx.showModal({
          title: 'OTA升级提示',
          content: '已发送固件更新命令,请等待设备更新和重启!'
        });
      }
    });
  },

  /*
  // OTA升级功能
  saveOtaSettings: function () {
    // 如果没有可更新固件，则不执行任何操作
    if (!this.data.hasUpdate) {
      // 删除无可用更新的弹窗提示
      return
    }

    // 执行OTA升级
    // 这里是OTA升级的占位实现，实际开发时需要替换为真实的OTA升级逻辑
    wx.showLoading({
      title: '正在升级中...',
      mask: true,
    })

    // 模拟OTA升级过程
    setTimeout(() => {
      wx.hideLoading()

      // 显示升级成功提示
      this.showCustomToast('升级成功', 'success')

      // 重置状态
      this.setData({
        hasUpdate: false,
        otaStatusText: '升级已完成，设备已是最新版本',
        showOtaUpdate: false,
        semiCircleHidden: false,
      })

      // 注释：实际开发时，这里应该调用设备的OTA升级接口
      // 例如：this.startOtaUpgrade(this.data.device.id, firmwareUrl)
      // 其中firmwareUrl是固件下载地址，可以从检测更新的接口获取
    }, 3000) // 模拟3秒的升级时间
  },*/

  // 切换通道启用状态，优化setData调用
  toggleChannelEnabled: function (e) {
    const index = e.currentTarget.dataset.index;
    const channelConfigs = this.data.channelConfigs;
    channelConfigs[index].enabled = !channelConfigs[index].enabled;
    this.setData({
      channelConfigs: channelConfigs
    })
    console.log("channelConfigs:" + JSON.stringify(this.data.channelConfigs))
  },

  // 恢复默认通道配置
  restoreDefaultChannelConfig: function () {
    try {
      // 使用通道配置工具获取默认配置
      const defaultChannelConfigs = this.data.originalChannelConfigs

      // 更新临时副本的界面数据
      this.setData({
        channelConfigs: defaultChannelConfigs
      });

      this.showCustomToast('已恢复默认通道配置，请保存生效', 'success'); // 提示用户需要保存
    } catch (e) {
      console.error('恢复默认通道配置失败', e);
      //logger.error('恢复默认通道配置失败', e);
      this.showCustomToast('恢复默认失败', 'error');
    }
  },

  // 保存通道配置
  saveChannelConfig: function () {
    let entityId = this.data.did
    let isGroup = 0
    const deviceType = this.data.device.deviceType // **获取 deviceType**
    if (!entityId || !deviceType) { // **检查 deviceType**
      console.error('saveChannelConfig: 无法确定实体ID或设备类型')
      return
    }

    try {
      if (JSON.stringify(this.data.channelConfigs) != JSON.stringify(this.data.originalChannelConfigs)) {
        const chs = []
        this.data.channelConfigs.forEach(ele => {
          chs.push({
            n: ele.n,
            nm: ele.name,
            c: ele.color,
            u: ele.enabled ? 1 : 0
          })
        })
        storageService.saveDeviceChannels(this.data.did, chs)

        //处理其他保存的渠道数据
        const advancedData = storageService.getAdvancedModeData(this.data.did, 0, this.data.device.deviceType)
        if (advancedData.curves != null && advancedData.curves.length > 0) {
          //console.log(advancedData.curves)
          for (var i = 0; i < advancedData.curves.length; i++) {
            let data = advancedData.curves[i].data
            let newData = {}
            chs.forEach(ele => {
              if (ele.u == 1) {
                let oldData = data[ele.n]
                if (oldData == null) {
                  oldData = [{
                      "time": 8,
                      "brightness": 0
                    },
                    {
                      "time": 20,
                      "brightness": 0
                    }
                  ]
                }
                newData[ele.n] = oldData
              }
            })
            advancedData.curves[i].data = newData
          }
          storageService.saveAdvancedModeData(this.data.did, {
            curves: advancedData.curves
          }, 0, this.data.device.deviceType)
        }
        const playerData = storageService.getPlayerModeData(this.data.did, 0, this.data.device.deviceType)
        if (playerData.presets != null && playerData.presets.length > 0) {
          for (var i = 0; i < playerData.presets.length; i++) {
            let data = playerData.presets[i]
            for (var j = 0; j < data.channels.length; j++) {
              data.channels[j].nm = chs[j].nm
              data.channels[j].c = chs[j].c
              data.channels[j].u = chs[j].u
            }
          }
          storageService.savePlayerModeData(this.data.did, {
            presets: playerData.presets
          }, 0, this.data.device.deviceType)
        }
      }
      this.showCustomToast('设置已保存', 'success')
      this.setData({
        showChannelConfig: false,
        semiCircleHidden: false,
        originalChannelConfigs: null, // 清除原始备份
      })
    } catch (e) {
      console.error('保存通道配置失败', e)
      this.showCustomToast('保存失败', 'error')
    }
  },

  // 保存散热设置
  saveCoolingSettings: function () {
    let entityId = this.data.did
    const deviceType = this.data.device.deviceType // **获取 deviceType**
    if (!entityId || !deviceType) { // **检查 deviceType**
      console.error('saveCoolingSettings: 无法确定实体ID或设备类型')
      return
    }

    const $t = this;
    setTimeout(() => { //防止参数值为生效
      storageService.saveTempInfo($t.data.did, {
        fanStartTemp: $t.data.fanStartTemp,
        ntcDiffTemp: $t.data.ntcDiffTemp
      })
      let pdata = {
        "st": appInstance.globalData.tempArr[parseInt($t.data.fanStartTemp) + parseInt($t.data.ntcDiffTemp)],
        "sp": appInstance.globalData.tempArr[parseInt($t.data.fanStartTemp) + parseInt($t.data.ntcDiffTemp) - 5],
        "b": $t.data.ntcDiffTemp
      };
      if (!this.data.isGroup) {
        appInstance.sendMtMsg($t.data.device.topicSend, "updateTemp", pdata, function (error) {
          if (error) {
            $t.showCustomToast('设置保存失败', 'error')
          } else {
            $t.showCustomToast('设置已保存', 'success')
            $t.setData({
              originalCoolingSettings: null
            })
          }
        });
      } else {
        let flgErr = fasle
        for (let i = 0; i < $t.data.devices.length; i++) {
          appInstance.sendMtMsg($t.data.devices[i].topicSend, "updateTemp", pdata, function (error) {
            if (error) {
              flgErr = true
            }
          })
          if (flgErr) {
            break
          }
        }
        if (flgErr) {
          $t.showCustomToast('设置保存失败', 'error')
        } else {
          $t.showCustomToast('设置已保存', 'success')
          $t.setData({
            originalCoolingSettings: null
          })
        }
      }
    }, 200);
  },

  // 保存临时开关设置
  saveTempSwitch: function () {
    let entityId = this.data.did
    let isGroup = this.data.isGroup
    const deviceType = this.data.device.deviceType // **获取 deviceType**
    if (!entityId || !deviceType) { // **检查 deviceType**
      console.error('saveTempSwitch: 无法确定实体ID或设备类型')
      return
    }

    try {
      const index = this.data.lightModeIndex;
      let modeType = 'player';

      const tempSwitchSettings = {
        lightModeIndex: index,
        modeType: modeType,
        modeName: this.data.lightModes[index],
        tempSwitchDuration: this.data.tempSwitchDuration,
      }

      console.log(`保存临时开关设置: 模式=${tempSwitchSettings.modeName}, 类型=${modeType}, 时长=${tempSwitchSettings.tempSwitchDuration}分钟`);

      let vArr = [];
      if (this.data.presets.length > 0) {
        this.data.presets[index].channels.forEach(ele => {
          vArr.push(ele.v)
        })
      }
      let flag = false
      vArr.forEach(ele => {
        if (ele > 0) {
          flag = true
        }
      })
      if (!flag) {
        wx.showModal({
          title: '提示',
          content: '你所选择的灯光模式灯光强度兼为0，设置失败！'
        })
        return
      }
      storageService.saveModeSettingData(
        entityId, {
          tempSwitchSettings: tempSwitchSettings
        },
        isGroup,
        deviceType // **传递 deviceType**
      )

      const $t = this;
      wx.showLoading({
        title: 'Loading......',
        mask: true,
        success: function () {
          let obj = {
            handM: $t.data.tempSwitchDuration,
            tl: vArr
          };
          $t.sendSyncToDeviceDialogResult(obj)
        }
      });
    } catch (e) {
      console.error('保存临时开关设置失败', e)
      this.showCustomToast('保存失败', 'error')
    }
  },

  // 显示自定义Toast，使用批量更新
  showCustomToast: function (text, type) {
    this.batchUpdate({
      showCustomToast: true,
      toastText: text,
      toastType: type,
    });

    // 500毫秒后自动隐藏，给用户足够的时间看清提示内容
    setTimeout(() => {
      this.batchUpdate({
        showCustomToast: false,
      });
    }, 1500);
  },

  // 输入风扇启动温度
  inputFanStartTemp: function (e) {
    const inputValue = e.detail.value
    // 如果输入为空，保持编辑状态但不更新校准后温度
    if (inputValue === '') {
      this.setData({
        fanStartTemp: inputValue,
        // 不更新fanStartTempDisplay以保持原值显示
      })
      return
    }

    // 计算校准后的显示值
    const calibratedValue = Number(inputValue) + Number(this.data.ntcDiffTemp)

    this.setData({
      fanStartTemp: inputValue,
      fanStartTempDisplay: calibratedValue,
      // 不再自动保存到存储，而是等待用户点击保存按钮
    })
  },

  // 风扇启动温度输入框获取焦点
  onFanTempFocus: function () {
    // 保存原始值，但清空输入框以便用户输入新值
    this.setData({
      originalFanStartTempValue: this.data.fanStartTemp, // 存储原始值
      fanStartTemp: '', // 清空输入框以便用户输入
      isFanTempEditing: true // 标记正在编辑状态，保持显示校准后温度
    })
  },

  // 风扇启动温度输入框失去焦点
  onFanTempBlur: function () {
    // 如果输入框为空，恢复原始值
    if (this.data.fanStartTemp === '') {
      this.setData({
        fanStartTemp: this.data.originalFanStartTempValue || '40', // 如果原始值不存在，使用默认值30
        fanStartTempDisplay: Number(this.data.originalFanStartTempValue || '40') + Number(this.data.ntcDiffTemp),
        isFanTempEditing: false
      })
      return
    }

    // 确保数值有效
    if (isNaN(Number(this.data.fanStartTemp))) {
      this.setData({
        fanStartTemp: this.data.originalFanStartTempValue || '40',
        fanStartTempDisplay: Number(this.data.originalFanStartTempValue || '40') + Number(this.data.ntcDiffTemp),
        isFanTempEditing: false
      })
      console.warn('Invalid fanStartTemp input on blur:', this.data.fanStartTemp)
      return
    }

    // 确保显示值正确更新
    const calibratedValue = Number(this.data.fanStartTemp) + Number(this.data.ntcDiffTemp)
    this.setData({
      fanStartTempDisplay: calibratedValue,
      isFanTempEditing: false
    })
  },

  // 输入温度校准值
  inputntcDiffTemp: function (e) {
    // 限制温度校准值在±10范围内
    let value = e.detail.value

    // 允许输入负号
    if (value === '-') {
      this.setData({
        ntcDiffTemp: value,
      })
      return
    }

    value = Number(value)
    if (value > 10) value = 10
    if (value < -10) value = -10

    // 计算校准后的温度显示值
    const calibratedValue = Number(this.data.fanStartTemp) + value

    this.setData({
      ntcDiffTemp: value,
      fanStartTempDisplay: calibratedValue,
      // 不再自动保存到存储，而是等待用户点击保存按钮
    })
  },

  // 温度校准值输入框获取焦点
  onntcDiffTempFocus: function () {
    this.setData({
      ntcDiffTemp: '',
    })
  },

  // 温度校准值输入框失去焦点 (Revised: No default setting on blur, ensure range)
  onntcDiffTempBlur: function () {
    // Validate range if not empty, but don't set default. Revert handles cancellation.
    if (this.data.ntcDiffTemp !== '' && this.data.ntcDiffTemp !== '-') {
      let value = Number(this.data.ntcDiffTemp)
      let changed = false
      if (isNaN(value)) {
        console.warn('Invalid ntcDiffTemp input on blur:', this.data.ntcDiffTemp)
        // Rely on closeAllPopups to revert
        value = this.data.originalCoolingSettings ?
          this.data.originalCoolingSettings.ntcDiffTemp :
          0 // Fallback needed?
        changed = true // Force update if invalid
      } else {
        if (value > 10) {
          value = 10
          changed = true
        }
        if (value < -10) {
          value = -10
          changed = true
        }
      }

      // Only update if the clamped value is different or was invalid
      if (changed || value !== this.data.ntcDiffTemp) {
        const calibratedValue = Number(this.data.fanStartTemp) + value
        // Don't setData here, let inputntcDiffTemp handle it,
        // or rely on revert from closeAllPopups if user cancels.
        // If we setData here, it bypasses the cancel mechanism partially.
        // Let's remove the setData from blur.
        // this.setData({
        //     ntcDiffTemp: value,
        //     fanStartTempDisplay: calibratedValue
        // });
      }
    } else if (this.data.ntcDiffTemp === '-') {
      // If only '-' is left, revert logic will handle it.
    }
  },

  // 打开通道编辑弹窗
  openChannelEdit: function (e) {
    const index = e.currentTarget.dataset.index;
    const channelConfig = this.data.channelConfigs[index];

    this.setData({
      showChannelEdit: true,
      editingChannel: { // editingChannel 仍然用于弹窗内的临时编辑
        index: index,
        name: channelConfig.name,
        color: channelConfig.color,
        // originalName: channelConfig.name, // 可以考虑增加原始值用于取消编辑弹窗
        // originalColor: channelConfig.color,
      },
    });
  },

  // 输入通道名称
  inputChannelName: function (e) {
    this.setData({
      'editingChannel.name': e.detail.value,
    });
  },

  // 选择颜色
  selectColor: function (e) {
    const color = e.currentTarget.dataset.color;
    this.setData({
      'editingChannel.color': color,
    });
  },

  // 取消通道编辑 (弹窗内的小编辑弹窗的取消)
  cancelChannelEdit: function () {
    this.setData({
      showChannelEdit: false,
      editingChannel: null, // 清空编辑中的通道信息
    });
  },

  // 保存通道编辑 (弹窗内的小编辑弹窗的保存)
  saveChannelEdit: function () {
    const index = this.data.editingChannel.index;
    const channelConfigs = JSON.parse(JSON.stringify(this.data.channelConfigs));

    channelConfigs[index].name = this.data.editingChannel.name;
    channelConfigs[index].color = this.data.editingChannel.color;

    // 记录日志
    console.log(`通道${index}编辑已暂存: 名称=${channelConfigs[index].name}, 颜色=${channelConfigs[index].color}`);

    this.setData({
      channelConfigs: channelConfigs,
      showChannelEdit: false,
      editingChannel: null,
    });

    // 不再自动触发保存 this.saveChannelConfig(); 而是等待用户点击侧弹窗的"保存设置"
    // this.saveChannelConfig();
  },

  // 处理button1(008.png)按钮点击事件
  handleButton1Click: function (e) {
    wx.navigateTo({
      url: `../player_mode/player_mode?did=${this.data.did}`,
      success: function () {
        // 跳转到玩家模式页面成功
      },
      fail: function (error) {
        console.error('跳转到玩家模式页面失败', error)
      },
    })
  },

  // 处理button2(009.png)按钮点击事件
  handleButton2Click: function (e) {
    // 跳转到高阶模式页面
    wx.navigateTo({
      url: `../advanced_mode/advanced_mode?did=${this.data.did}`,
      success: function () {
        // 跳转成功
      },
      fail: function (error) {
        console.error('跳转到高阶模式页面失败', error)
      },
    })
  },
  // 处理按钮3点击事件，跳转到玩家模式页面
  handleButton3Click: function () {
    // 跳转到玩家模式页面，修正了错误跳转
    wx.navigateTo({
      url: `../player_mode/player_mode?did=${this.data.did}`,
      success: function () {
        // 跳转到玩家模式页面成功
      },
      fail: function (error) {
        console.error('跳转到玩家模式页面失败', error)
      }
    })
  },
  // 处理button4(009.png)按钮点击事件
  handleButton4Click: function (e) {
    // 跳转到高阶模式页面
    wx.navigateTo({
      url: `../advanced_mode/advanced_mode?did=${this.data.did}`,
      success: function () {
        // 跳转成功
      },
      fail: function (error) {
        console.error('跳转到高阶模式页面失败', error)
      },
    })
  },

  // 选择灯光模式
  bindLightModeChange: function (e) {
    const index = parseInt(e.detail.value);
    this.setData({
      lightModeIndex: index,
      // 不再自动保存到存储，而是等待用户点击保存按钮
    });

    // 添加日志以便于调试选择的模式
    let categoryName = '';
    if (index < 1) {
      categoryName = '基础预设模式';
    } else if (index >= 1 && index < 8) {
      categoryName = '快捷模式预设';
    } else {
      categoryName = '玩家模式预设';
    }
    console.log(`选择了模式: ${this.data.lightModes[index]} (${categoryName})`);
  },

  // 临时开关时长输入框获取焦点
  onTempSwitchFocus: function () {
    this.setData({
      tempSwitchDuration: '',
    })
  },

  // 临时开关时长输入框失去焦点 (Revised: No default setting on blur)
  onTempSwitchBlur: function () {
    // Validate if not empty, but don't set default. Revert handles cancellation.
    if (
      this.data.tempSwitchDuration !== '' &&
      (isNaN(Number(this.data.tempSwitchDuration)) || Number(this.data.tempSwitchDuration) < 0)
    ) {
      console.warn('Invalid tempSwitchDuration input on blur:', this.data.tempSwitchDuration)
      // Rely on closeAllPopups to revert.
    }
  },

  // 输入临时开关时长
  inputTempSwitchDuration: function (e) {
    this.setData({
      tempSwitchDuration: e.detail.value,
      // 不再自动保存到存储，而是等待用户点击保存按钮
    })
  },

  // 处理页面点击事件
  onPageTap: function (e) {
    // 获取点击的目标元素的dataset
    const dataset = e.target.dataset || {}

    // 检查是否点击了需要保持打开的区域
    const isClickedKeepArea = dataset.keepOpen === 'true'

    // 如果点击的不是需要保持打开的区域，且有任何弹出模块处于显示状态，则关闭所有弹出模块
    if (
      !isClickedKeepArea &&
      (this.data.showSettingsPopup ||
        this.data.showCoolingSettings ||
        this.data.showChannelConfig ||
        this.data.showTempSwitch ||
        this.data.showOtaUpdate)
    ) {
      this.closeAllPopups()
    }
  },

  // 处理按钮点击事件
  handleButtonClick: function (e) {
    // 获取点击的按钮ID
    const buttonId = e.currentTarget.id

    // 检查按钮是否在中间位置
    if (this.data.centerButtonId === buttonId) {
      // 跳转到快捷模式页面
      wx.navigateTo({
        url: `../shortcut_mode/shortcut_mode?did=${this.data.did}`,
        success: function () {},
        fail: function (error) {
          console.error('跳转到快捷模式页面失败', error)
        },
      })
    }
  },

  // 阻止事件冒泡
  stopPropagation: function (e) {
    // 阻止事件冒泡到页面
  },

  // 修改散热设置的滑块事件，使用防抖
  fanStartTempChange: function (e) {
    const value = e.detail.value;
    // 使用batchUpdate替代直接setData
    this.batchUpdate({
      fanStartTemp: value,
      fanStartTempDisplay: value + this.data.ntcDiffTemp
    });
  },

  // 修改温度校准的滑块事件，使用防抖
  ntcDiffTempChange: function (e) {
    const value = e.detail.value;
    // 使用batchUpdate替代直接setData
    this.batchUpdate({
      ntcDiffTemp: value,
      fanStartTempDisplay: this.data.fanStartTemp + value
    });
  },

  // 配置数据相关函数
  toggleConfigData: function () {
    // 1. 首先恢复其他弹窗的未保存更改
    this._revertOtherPopups('configData') // 排除自身

    // 2. 现在处理配置数据弹窗本身
    const newShowConfigData = !this.data.showConfigData
    if (newShowConfigData) {
      // 打开时获取当前设备的所有配置数据
      this.getCurrentDeviceConfigData();

      // 打开：备份当前状态
      this.setData({
        showConfigData: true,
        showCoolingSettings: false, // 确保其他弹窗都已关闭
        showChannelConfig: false,
        showTempSwitch: false,
        showOtaUpdate: false, // 同时关闭OTA
        semiCircleHidden: true,
      })
    } else {
      // 关闭弹窗
      this.setData({
        showConfigData: false,
        semiCircleHidden: false // 关闭时显示半圆
      })
    }
  },

  // 获取当前设备的配置数据
  getCurrentDeviceConfigData: function () {
    const entityId = this.data.device.deviceId
    const isGroup = this.data.isGroup
    const deviceType = this.data.device.deviceType

    if (!entityId || !deviceType) {
      console.error('获取设备配置数据失败: 无法确定实体ID或设备类型')
      return
    }

    // 获取所有保存的配置列表
    const savedConfigs = storageService.getConfigList(this.data.did)

    // 获取当前设备的配置数据
    this.setData({
      savedConfigs: savedConfigs,
      // 重置为默认配置名称
      configName: '输入配置名称'
    })
  },

  // 监听配置名称输入
  inputConfigName: function (e) {
    this.setData({
      configName: e.detail.value
    })
  },

  // 配置名输入框获取焦点
  onConfigNameFocus: function () {
    // 如果是默认值，则清空
    if (this.data.configName === '输入配置名称') {
      this.setData({
        configName: ''
      })
    }
  },

  // 配置名输入框失去焦点
  onConfigNameBlur: function () {
    // 如果为空，则恢复默认值
    if (!this.data.configName.trim()) {
      this.setData({
        configName: '输入配置名称'
      })
    }
  },

  // 构建当前设备的配置数据
  buildCurrentConfigData: function () {
    const entityId = this.data.did
    const isGroup = 0
    const deviceType = this.data.device.deviceType

    try {
      // 确保配置名称有意义
      let configName = this.data.configName;
      if (configName === '输入配置名称' || !configName.trim()) {
        configName = '默认配置';
      }
      const backupData = storageService.genBackupData(this.data.did)
      const configData = {
        deviceType: deviceType,
        deviceId: entityId, // 保存设备ID以便于识别
        name: configName,
        timestampStr: this.formatTime(new Date().getTime()), // 时间戳
        backupTime: new Date().toISOString(),
        backupData: backupData
      }


      // 保存到数据中
      this.setData({
        currentConfigData: configData
      })

      console.log('已构建完整配置数据:', JSON.stringify(configData).length + ' 字节')
      return configData
    } catch (e) {
      console.error('构建配置数据失败', e)
      return null
    }
  },

  // 打开配置管理弹窗
  openConfigManager: function () {
    this.setData({
      showConfigManager: true
    })
  },

  // 关闭配置管理弹窗
  closeConfigManager: function () {
    this.setData({
      showConfigManager: false,
      selectedConfigIndex: -1
    })
  },

  // 格式化时间戳
  formatTime: function (timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`;
  },

  // 数字补零
  padZero: function (num) {
    return num < 10 ? '0' + num : num;
  },

  // 备份当前设备配置
  backupDeviceConfig: function () {
    // 构建当前配置数据
    const configData = this.buildCurrentConfigData()

    if (!configData) {
      this.showCustomToast('获取当前配置数据失败', 'error')
      return
    }

    try {
      // 获取已保存的配置列表
      const deviceType = this.data.device.deviceType
      let savedConfigs = storageService.getConfigList(this.data.did)

      // 检查是否超过最大保存数量
      if (savedConfigs.length >= this.data.maxConfigsCount) {
        // 删除最旧的配置
        savedConfigs.shift()
      }

      // 添加新配置到列表
      savedConfigs.push(configData)

      // 保存更新后的配置列表
      storageService.saveConfigList(this.data.did, savedConfigs)
      this.setData({
        savedConfigs: savedConfigs
      })
      this.showCustomToast('配置已备份', 'success')
    } catch (e) {
      console.error('备份设备配置失败', e)
      this.showCustomToast('配置备份失败', 'error')
    }
  },

  // 选择配置
  selectConfig: function (e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      selectedConfigIndex: index
    })
  },

  // 还原选中的配置
  restoreSelectedConfig: function (e) {
    const index = e.currentTarget.dataset.index
    this.applySelectedConfig(index)
  },

  // 编辑配置名称
  editConfigName: function (e) {
    const index = e.currentTarget.dataset.index
    const config = this.data.savedConfigs[index]

    if (!config) return

    wx.showModal({
      title: '修改配置名称',
      content: '请输入新的配置名称',
      editable: true,
      placeholderText: config.name,
      success: res => {
        if (res.confirm && res.content) {
          // 修改配置名称
          let configs = [...this.data.savedConfigs]
          configs[index].name = res.content

          // 保存更新后的配置列表
          storageService.saveConfigList(this.data.did, configs)
          this.setData({
            savedConfigs: configs
          })
          this.showCustomToast('名称已修改', 'success')
        }
      }
    })
  },

  // 删除选中的配置
  deleteSelectedConfig: function (e) {
    const index = e.currentTarget.dataset.index

    wx.showModal({
      title: '删除确认',
      content: '确定要删除此配置吗？',
      success: res => {
        if (res.confirm) {
          let savedConfigs = [...this.data.savedConfigs]
          savedConfigs.splice(index, 1)
          this.setData({
            savedConfigs: savedConfigs
          })
          // 保存更新后的配置列表
          storageService.saveConfigList(this.data.did, savedConfigs)
          this.showCustomToast('配置已删除', 'success')
        }
      }
    })
  },

  // 应用选中的配置
  applySelectedConfig: function (index) {
    // 获取选中的配置
    const config = this.data.savedConfigs[index]
    if (!config) {
      this.showCustomToast('未找到选中的配置', 'error')
      return
    }
    // 应用配置
    this.restoreBackupData(this.data.did, config.backupData)
  },

  restoreBackupData(entityId, backupData) {
    try {
      // 显示正在应用配置的加载提示
      wx.showLoading({
        title: '正在应用配置...',
        mask: true
      })
      storageService.restoreBackupData(entityId, backupData)

      // 保存扩展设置数据
      if (backupData.temp) {
        // 立即更新当前页面中的散热设置数据
        const tempObj = backupData.temp
        this.setData({
          fanStartTemp: tempObj.fanStartTemp || '40',
          ntcDiffTemp: tempObj.ntcDiffTemp || '0',
          fanStartTempDisplay: Number(tempObj.fanStartTemp || '40') + Number(tempObj.ntcDiffTemp || '0')
        })
      }

      if (backupData.tempSwitchSettings) {
        // 立即更新当前页面中的临时开关数据
        this.setData({
          lightModeIndex: backupData.tempSwitchSettings.lightModeIndex || 0,
          tempSwitchDuration: backupData.tempSwitchSettings.tempSwitchDuration || '40'
        })
      }

      // 隐藏加载提示
      wx.hideLoading()

      this.showCustomToast('配置已还原', 'success')

      // 关闭配置管理弹窗
      this.setData({
        showConfigManager: false,
        selectedConfigIndex: -1
      })

      // 关闭配置数据弹窗
      setTimeout(() => {
        this.setData({
          showConfigData: false,
          semiCircleHidden: false
        })

        // 刷新当前页面
        this.onShow()
      }, 300)
    } catch (e) {
      wx.hideLoading()
      console.error('应用配置失败', e)
      this.showCustomToast('配置还原失败', 'error')
    }
  },

  // 导出配置码
  exportConfigCode: function () {
    // 构建当前配置数据
    const configData = this.buildCurrentConfigData()

    if (!configData) {
      this.showCustomToast('获取当前配置数据失败', 'error')
      return
    }

    // 显示加载中
    wx.showLoading({
      title: '正在生成分享码...',
      mask: true
    })

    try {
      // 将配置数据转换为BASE64字符串
      const configStr = JSON.stringify(configData)

      // 记录一下原始数据大小
      const originalSize = configStr.length

      // 尝试压缩数据（我们不能直接使用压缩库，但可以简单处理）
      //let processedData = configStr

      // 将长JSON转换为BASE64编码
      // const configCode = wx.arrayBufferToBase64(new Uint8Array([...new TextEncoder().encode(processedData)]).buffer)
      const configCode = Base64.encode(configStr)

      // 隐藏加载提示
      wx.hideLoading()

      // 显示分享码生成成功和数据大小信息
      this.setData({
        showShareCodeResult: true,
        shareCodeData: {
          code: configCode,
          size: Math.round(configCode.length / 1024 * 100) / 100, // KB格式，保留两位小数
          timestampStr: this.formatTime(new Date().getTime()),
          deviceName: this.data.device?.name || '未知设备',
          deviceType: this.data.device?.deviceType || '未知类型'
        }
      })
    } catch (e) {
      wx.hideLoading()
      console.error('导出配置码失败', e)
      this.showCustomToast('生成分享码失败', 'error')
    }
  },

  // 关闭分享码结果弹窗
  closeShareCodeResult: function () {
    this.setData({
      showShareCodeResult: false
    })
  },

  // 复制分享码到剪贴板
  copyShareCode: function () {
    const shareCode = this.data.shareCodeData?.code
    if (!shareCode) {
      this.showCustomToast('未找到分享码', 'error')
      return
    }

    wx.setClipboardData({
      data: shareCode,
      success: () => {
        this.showCustomToast('分享码已复制到剪贴板', 'success')
      },
      fail: () => {
        this.showCustomToast('复制失败', 'error')
      }
    })
  },

  // 保存分享码为图片
  saveShareCodeImage: function () {
    if (!this.data.shareCodeData) {
      this.showCustomToast('未找到分享码数据', 'error')
      return
    }

    // 小程序没有直接的方式保存生成的图片，但可以将数据传递给服务器生成，
    // 或者使用canvas绘制二维码并保存。这里简单处理，先复制到剪贴板
    this.copyShareCode()
    this.showCustomToast('已复制分享码，您可以粘贴保存', 'success')
  },

  // 导入配置码
  importConfigCode: function () {
    // 显示自定义导入弹窗
    this.setData({
      showImportCodeModal: true,
      importCodeValue: ''
    });
  },

  // 关闭导入配置码弹窗
  closeImportCodeModal: function () {
    this.setData({
      showImportCodeModal: false
    });
  },

  // 监听导入码输入
  inputImportCode: function (e) {
    // 无需截断分享码，保存完整的分享码内容
    this.setData({
      importCodeValue: e.detail.value
    });
  },

  // 提交导入配置码
  submitImportCode: function () {
    const code = this.data.importCodeValue;
    if (!code.trim()) {
      this.showCustomToast('请输入配置码', 'error');
      return;
    }

    // 关闭弹窗
    this.setData({
      showImportCodeModal: false
    });

    // 应用配置码
    this.applyConfigCode(code);
  },

  // 从剪贴板粘贴配置码
  pasteImportCode: function () {
    wx.getClipboardData({
      success: (res) => {
        if (res.data) {
          this.setData({
            importCodeValue: res.data
          });
        } else {
          this.showCustomToast('剪贴板为空', 'error');
        }
      },
      fail: () => {
        this.showCustomToast('获取剪贴板失败', 'error');
      }
    });
  },

  // 应用配置码
  applyConfigCode: function (code) {
    // 解码配置数据
    //const decodedStr = wx.base64ToArrayBuffer(code)
    //const configStr = new TextDecoder().decode(new Uint8Array(decodedStr))
    const configStr = Base64.decode(code)
    const configData_t = JSON.parse(configStr)
    const configData = {
      backupData: {}
    }

    for (const key in configData_t) {
      if (key === "backupData") {
        for (const key2 in configData_t[key]) {
          const val = configData_t[key][key2]
          if (typeof val === "string") {
            if (val.startsWith("{") || val.startsWith("[")) {
              configData.backupData[key2] = JSON.parse(val)
            } else {
              configData.backupData[key2] = val
            }
          } else {
            configData.backupData[key2] = val
          }
        }
      } else {
        configData[key] = configData_t[key]
      }
    }

    // 检查设备类型是否匹配
    if (configData.deviceType !== this.data.device.deviceType) {
      this.showCustomToast('配置码与当前设备类型不匹配', 'error')
      return
    }
    let flag = false
    const backupChs = configData.backupData.ch
    if (!backupChs || !Array.isArray(backupChs)) {
      flag = true
    } else {
      const chs = storageService.getDeviceChannels(this.data.did)
      if (chs.length != backupChs.length) {
        flag = true
      } else {
        for (let i = 0; i < chs.length; i++) {
          if (chs[i].n != backupChs[i].n) {
            flag = true
            break
          }
        }
      }
    }
    if (flag) {
      console.log(configData)
      this.showCustomToast('设备通道不匹配', 'error')
      return
    }

    this.restoreBackupData(this.data.did, configData.backupData)
  },

  // 管理已保存的配置
  manageSavedConfigs: function () {
    // 打开配置列表管理界面
    wx.showActionSheet({
      itemList: this.data.savedConfigs.length > 0 ?
        this.data.savedConfigs.map(config => `${config.name} (${new Date(config.timestamp).toLocaleString()})`) : ['暂无保存的配置'],
      success: res => {
        if (this.data.savedConfigs.length > 0) {
          const index = res.tapIndex
          // 弹出二级菜单，选择操作
          wx.showActionSheet({
            itemList: ['应用此配置', '删除此配置'],
            success: subRes => {
              if (subRes.tapIndex === 0) {
                // 应用配置
                this.applySelectedConfig(index)
              } else if (subRes.tapIndex === 1) {
                // 删除配置
                this.deleteSelectedConfig(index)
              }
            }
          })
        }
      }
    })
  },

  // 恢复函数
  restoreConfigData: function () {
    // 恢复原始配置数据设置
    if (this.data.originalConfigData) {
      this.setData({
        deviceModel: this.data.originalConfigData.deviceModel,
        firmwareVersion: this.data.originalConfigData.firmwareVersion,
        maxPower: this.data.originalConfigData.maxPower,
        originalConfigData: null // 清除备份
      })
    }
  },

  restoreCoolingSettings: function () {
    // 恢复原始散热设置
    if (this.data.originalCoolingSettings) {
      this.setData({
        fanStartTemp: this.data.originalCoolingSettings.fanStartTemp,
        ntcDiffTemp: this.data.originalCoolingSettings.ntcDiffTemp,
        fanStartTempDisplay: this.data.originalCoolingSettings.fanStartTempDisplay,
        originalCoolingSettings: null // 清除备份
      })
    }
  },

  restoreTempSwitchSettings: function () {
    // 恢复原始临时开关设置
    if (this.data.originalTempSwitchSettings) {
      this.setData({
        lightModeIndex: this.data.originalTempSwitchSettings.lightModeIndex,
        tempSwitchDuration: this.data.originalTempSwitchSettings.tempSwitchDuration,
        originalTempSwitchSettings: null // 清除备份
      })
    }
  },

  sendSyncToDeviceDialogResult(obj) {
    const $t = this
    if (!$t.data.isGroup) {
      appInstance.sendMtMsg($t.data.device.topicSend, "syncHandUp", obj)
      $t.data.timeoutObj = setTimeout(function () {
        $t.confirmPopSyncToDeviceDialogResult(0);
      }, 5000);
    } else {
      $t.data.syncNum = 0
      $t.data.devices.forEach(device => {
        appInstance.sendMtMsg(device.topicSend, "syncHandUp", obj);
      })
      $t.data.timeoutObj = setTimeout(function () {
        $t.confirmPopSyncToDeviceDialogResultGroup(0);
      }, 8000);
    }
  },
  confirmPopSyncToDeviceDialogResult(succ) {
    wx.hideLoading();
    if (succ == 0) {
      this.setData({
        showTempSwitch: false,
        semiCircleHidden: false,
        originalTempSwitchSettings: null, // 清除原始备份
      })
      wx.showModal({
        title: '提示',
        content: '设置已保存但同步数据到设备失败！'
      })
    } else {
      this.showCustomToast('设置已保存并同步到设备', 'success')
      clearTimeout(this.data.timeoutObj);
      storageService.setTmpSynced(this.data.did)
    }
  },
  confirmPopSyncToDeviceDialogResultGroup(succ) {
    if (succ == 1) {
      this.data.syncNum++
    }
    if (this.data.syncNum >= this.data.devices.length) {
      this.confirmPopSyncToDeviceDialogResult(1)
      return
    }
    if (succ == 0) {
      if (this.data.syncNum == 0) {
        this.confirmPopSyncToDeviceDialogResult(0)
      } else {
        wx.hideLoading()
        this.setData({
          showTempSwitch: false,
          semiCircleHidden: false,
          originalTempSwitchSettings: null, // 清除原始备份
        })
        wx.showModal({
          title: '提示',
          content: '设置已保存但同步数据到部分设备失败，请检查设备状态并重新操作。成功' + this.data.syncNum + '台，失败' + (this.data.devices.length - this.data.syncNum) + '台'
        })
      }
    }

  },

  onShow: function () {
    console.log("mode_setting onShow...")
    const $t = this;
    if (!this.data.isGroup) {
      wx.$event.on(this.data.device.topicSub, this, (obj) => {
        if (obj.type == "syncHandUp") {
          $t.confirmPopSyncToDeviceDialogResult(1);
        }
      })
    } else {
      this.data.devices.forEach(device => {
        wx.$event.on(device.topicSub, $t, (obj) => {
          if (obj.type == "syncHandUp") {
            $t.confirmPopSyncToDeviceDialogResultGroup(1);
          }
        })
      })
    }

    const presets = playerModeService.getPresets(this.data.did)
    this.setData({
      lightModes: presets.map(mode => mode.name)
    })
    this.data.presets = presets
  },

  // 页面卸载时保存数据
  onUnload: function () {
    console.log("mode_setting onUnload...")

    // 确定要保存的实体ID和类型
    let entityId = this.data.device.deviceId
    let isGroup = this.data.isGroup // Use the flag set during onLoad
    const deviceType = this.data.device.deviceType // **获取 deviceType**

    if (!entityId || !deviceType) { // **检查 deviceType**
      console.error('onUnload:无法确定保存的实体ID或设备类型')
      return
    }

    try {
      // 准备按钮数据
      const buttonData = {
        buttonStyles: this.data.buttonStyles,
        currentPositionIndex: this.data.currentPositionIndex,
        centerButtonId: this.data.centerButtonId,
      }

      // 只保存按钮数据，其他设置由各自的保存按钮处理
      if (buttonData) {
        // Ensure buttonData exists before saving
        storageService.saveModeSettingData(entityId, {
          buttonData: buttonData
        }, isGroup, deviceType) // **传递 deviceType**
      }
    } catch (e) {
      console.error('页面卸载时保存数据失败', e)
    }
  },

})